package com.jtkjbike.monitor.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.jtkjbike.monitor.modules.api.entity.BikeInfo;
import org.apache.commons.io.FileUtils;

import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 导出Excel的基础包
 */
public  class ExportExcelUtil {

    /**
     * 将一个集合导出为Excle并转换问文件流下载
     * @param fileName
     * @param list
     * @param pojoClass
     * @return
     */
    public static  ResponseEntity<Resource> downloadFile(String fileName, List list, Class<?> pojoClass) {
        ByteArrayOutputStream bos = null;
        try {
            Workbook workbook = ExportExcelUtil.creatExcel(fileName, list, pojoClass);
            bos = new ByteArrayOutputStream();
            workbook.write(bos);
            workbook.close();
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("charset", "utf-8");
            fileName=fileName+".xlsx";
            //设置下载文件名
            fileName = URLEncoder.encode(fileName, "UTF-8");
            headers.add("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            Resource resource = new InputStreamResource(new ByteArrayInputStream(bos.toByteArray()));
            return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType("application/x-msdownload")).body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }

    public static Workbook creatExcel(String title, List<?> list , Class<?> pojoClass){
        LinkedList<Object> exportList = new LinkedList<>();
        Workbook workbook = null;
        Date start = new Date();
        ExportParams params = new ExportParams(title, title);
        for(Object t:list){
            exportList.add(t);
            if(exportList.size() >= 10000){
                workbook = ExcelExportUtil.exportBigExcel(params,pojoClass, exportList);
                exportList.clear();
            }
        }
        workbook = ExcelExportUtil.exportBigExcel(params,pojoClass, exportList);
        ExcelExportUtil.closeExportBigExcel();
        return  workbook;
    }

    /**
     * 将一个集合导出为Excel文件并保存
     * @param title
     * @param list
     * @param pojoClass
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> exportExcel(String title, List<?> list , Class<?> pojoClass) throws IOException {
        List<Object> exportList = new ArrayList<>();
        Workbook workbook = null;
        Date start = new Date();
        ExportParams params = new ExportParams(title, title);
        for(Object t:list){
            exportList.add(t);
            if(exportList.size() >= 10000){
                workbook = ExcelExportUtil.exportBigExcel(params,pojoClass, exportList);
                exportList.clear();
            }
        }
        workbook = ExcelExportUtil.exportBigExcel(params,pojoClass, exportList);
        ExcelExportUtil.closeExportBigExcel();
        System.out.println(new Date().getTime() - start.getTime());
        File savefile = new File("excel");
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        FileOutputStream fos = null;
        String filePath="excel/"+title+".xlsx";
        try {

            fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return download(title,new File(filePath));
    }

    public  static ResponseEntity<byte[]> download(String fileName, File file) throws IOException {
        String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", dfileName);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
}
